import { tree, add, remove, edit, findDealer } from '../../../services/org';

export default {
  namespace: 'org',
  state: {
    dataList: [],
    treeData: [],
    treeDataNotDealer: [],
    loading: false,
    dealer: {
      list: [],
      pagination: {},
    },
  },
  effects: {
    *initData({ payload, callback }, { call, put }) {
      yield put({
        type: 'save',
        payload: {
          dataList: [],
          treeData: [],
          loading: false,
          details: {},
          detailsLoading: false,
        },
      });
    },
    // 获取组织机构树
    *fetchTree({ payload, callback }, { call, put }) {
      yield put({
        type: 'save',
        payload: { loading: true },
      });
      const response = yield call(tree, payload);
      yield put({
        type: 'save',
        payload: {
          treeData: response.data.map(item => {
            return { ...item, isRoot: true }
          }), loading: false
        },
      });
      if (callback) callback(response);
    },
    // 组织添加
    *add({ payload, callback }, { call, put }) {
      yield put({
        type: 'save',
        payload: { loading: true },
      });
      const response = yield call(add, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      yield put({
        type: 'save',
        payload: { loading: false },
      });
      if (callback) callback(response);
    },
    *edit({ payload, callback }, { call, put }) {
      const response = yield call(edit, payload);
      yield put({
        type: 'save',
        payload: { details: response.data },
      });
      if (callback) callback(response);
    },
    *remove({ payload, callback }, { call, put }) {
      const response = yield call(remove, payload);
      yield put({
        type: 'save',
        payload: { loading: false },
      });
      if (callback) callback(response);
    },
    // 获取组织机构详情
    *details({ payload, callback }, { call, put }) {
      yield put({
        type: 'save',
        payload: { detailsLoading: true },
      });
      const response = yield call(details, payload);
      yield put({
        type: 'save',
        payload: { details: response.data },
      });
      yield put({
        type: 'save',
        payload: { detailsLoading: false },
      });
      if (callback) callback(response);
    },
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
